<?php 
class ControllerLogin extends Controller { 
	var $error = array();
	        
	function index() { 
		$request  =& $this->locator->get('request');
		$response =& $this->locator->get('response');
		$url      =& $this->locator->get('url');
		$language =& $this->locator->get('language');
		$template =& $this->locator->get('template');
		$module   =& $this->locator->get('module');
		$user     =& $this->locator->get('user');

    	$language->load('controller/login.php');
    
		$template->set('title', $language->get('heading_title'));

		if ($user->isLogged()) {
			$controller=$request->gethtml('controller');
			if ($controller == 'login' || empty($controller)) {
				$response->redirect($url->ssl('home'));
			}
			else { $response->redirect($url->referer($url->ssl($controller))); }
		}
		
		if ($request->isPost() && $request->has('username', 'post') && $this->validate()) {
			$controller=$request->gethtml('controller');
			if ($controller == 'login' || empty($controller)) {
				$response->redirect($url->ssl('home'));
			}
			else { $response->redirect($url->referer($url->ssl($controller))); }
		}
	
    	$view = $this->locator->create('template');

		$view->set('tpl', $template);

    	$view->set('heading_title', $language->get('heading_title'));
    	$view->set('heading_description', $language->get('heading_description'));

    	$view->set('entry_username', $language->get('entry_username'));
    	$view->set('entry_password', $language->get('entry_password'));

    	$view->set('button_login', $language->get('button_login'));
		
		$view->set('error', @$this->error['message']);
 
		$view->set('action', $url->requested($url->ssl('home')));

		$view->set('username', $request->gethtml('username', 'post'));
    
		$template->set('content', $view->fetch('content/login.tpl'));

		$template->set($module->fetch());
			 
    	$response->set($template->fetch('layout.tpl'));
  	}
	
	function validate() {
		$request  =& $this->locator->get('request');
		$language =& $this->locator->get('language');
		$user     =& $this->locator->get('user');
				
		if (!$user->login($request->gethtml('username', 'post'), $request->gethtml('password', 'post'))) {
			$this->error['message'] = $language->get('error_login');
		}
		
		if (!$this->error) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	function isLogged() {
		$user =& $this->locator->get('user');
		
		if (!$user->isLogged()) {
			return $this->forward('login', 'index');
		}
	}
	
}  
?>
